/*
模块名称：用户登录

功能描述：
1、审核登录用户身份。
2、确定用户登录科室。

业务逻辑：
1、根据输入的用户代码，在 com_priv_user 和 com_department 提取用户可登录的科室名称。
2、核查用户身份和口令是否有效。
3、在com_loginlog表写入登录信息。

*/

#include "com_dialog_signin.h"
#include "ui_com_dialog_signin.h"
#include "pub_var.h"
#include <QDebug>
#include <QMessageBox>
#include <QKeyEvent>
#include <QSettings>
#include <QHostInfo>

Dialog_signin::Dialog_signin(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog_signin)
{
    ui->setupUi(this);
    errorCount = 0;
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qro_t = new QSqlQuery(pub::db_o);

    //设置本机工作参数
    QSettings setIni("clin.ini", QSettings::IniFormat);
    defaultDept = setIni.value("system/default_dept").toString();

    pub::DEBUG = (setIni.value("system/debug").toString() == "1" ? true : false);

    QString sq = "select * from com_hospitalinfo where valid_Flag = '1' ";

    if(pub::DEBUG )
    {
        //测试地址
        sq += " and mark = 'temp' ";
    }
    else
    {
        //正常地址
        sq += " and mark = 'normal' ";
    }

    qDebug()<<"提取本机医保工作参数："<<sq<<"\n";

    qrm->exec(sq);

    if(qrm->next())
    {
        pub::hos_name = qrm->value("hos_name").toString();
        pub::hos_code = qrm->value("hos_code").toString();
        pub::hos_ybbh = qrm->value("new_hos_ybbh").toString();    //医保编号

        pub::hos_insuplc = qrm->value("new_hos_insuplc").toString();    //参保区划
        //pub::hos_hiscode = qrm->value("new_hos_hiscode").toString(); //  开发商代码
        pub::hos_hiscode = "OwnSoft"; //  开发商代码
        pub::hos_secretcode = qrm->value("new_hos_secretcode").toString(); //  安全管理码
        pub::hos_ybbh_old = qrm->value("hos_ybbh").toString(); //  旧医保编号
        pub::hos_ybjy = qrm->value("new_hos_ybjy_ip").toString();    //医保交易中台
        pub::hos_dzpz = qrm->value("new_hos_dzpz_ip").toString();    //电子凭证中台

        pub::zj_push_ip = qrm->value("zj_push_ip").toString();    //诊间支付消息推送地址
        pub::app_id = qrm->value("zj_app_id").toString();    //诊间支付 app id
        pub::key_sm4 = qrm->value("zj_key_sm4").toString();    //诊间支付 密钥
        pub::key_pub_app = qrm->value("zj_key_pub_app").toString();    //诊间支付应用公钥
        pub::key_private_app = qrm->value("zj_key_private_app").toString();    //诊间支付应用私钥
        pub::key_pub_pub = qrm->value("zj_key_pub_pub").toString();    //诊间支付平台公钥

        QStringList addr = pub::hos_ybjy.split(":");
        pub::hos_ybjy_ip = addr[1].mid(2, addr[1].length() - 2);    //医保交易中台
        pub::hos_ybjy_port = addr[2].mid(0, addr[2].indexOf("/") );    //医保交易中台

    }
    else
    {
        QMessageBox::information(this,"error","Can not load system envirenment from MySQL!");
    }

    //pub::hos_name = qrm->value(0).toString();
    ui->lbHosName->setText(pub::hos_name);
    QFont f = ui->label->font();
    QString sty = "color: blue;font-size: " + QString::number(f.pointSize() * 1.5)+"pt;";
    ui->lbHosName->setStyleSheet(sty);


    ui->leUserCode->setFocus();

    ui->cbDepartment->clear();

    //接收默认事件的按钮不显示
    ui->pushButton->setVisible(false);


}

Dialog_signin::~Dialog_signin()
{
    delete ui;
}

void Dialog_signin::on_pbOk_clicked()
{

    if(ui->cbDepartment->currentText().isEmpty()){
        QMessageBox::warning(this, "注意", "输入的用户代码未关联诊室！");
        return;
    }


    if(ui->leUserCode->text().trimmed().isEmpty() ||
            ui->lePassword->text().trimmed().isEmpty() ){
        return;
    }

    QString sq = "select empl_code, empl_name, si_code "
                 " from com_employee where empl_code = '"
            + ui->leUserCode->text() + "'";
    sq += " and pswd = md5('" + ui->lePassword->text() + "')";
    qrm->exec(sq );

    if(qrm->next()){
        pub::usr_code = qrm->value(0).toString();
        pub::usr_name = qrm->value(1).toString();

        pub::dr_codg = qrm->value(2).toString();//医保代码

        pub::userValidated = true;

        qro->exec("select si_code,jszc,zyfw, senior_doct "
                  "from com_doctor_compare where empl_code = '"+pub::usr_code+"'");
        if(qro->next())
        {
            pub::dr_profttl = qro->value(1).toString(); //	医师职称	 字典表
            pub::dr_duty_range = qro->value(2).toString(); //执业范围
            pub::dr_senior = qro->value("senior_doct").toString(); //带教医师
        }

        qro->exec("select sid,serial# from v$session "
                  " where audsid = (select userenv('SESSIONID') From DUAL)");
        qro->next();
        QString sid = qro->value(0).toString();
        QString serial = qro->value(1).toString();

        qro->exec("SELECT SEQ_COM_LOGINSESSION.NEXTVAL FROM DUAL");
        qro->next();
        pub::LOGINSESSION = qro->value(0).toString();

        QString sql_str = "select log_index from com_loginlog "
                          " where trunc(login_date) = trunc(sysdate) and  empl_code = '";
        sql_str += pub::usr_code + "' and logout_date is null";

        qro->exec(sql_str);

        if(qro->next())
        {
            QMessageBox::StandardButton bt;
            bt = QMessageBox::question(this, "注意", "存在用户本日未注销登入记录，是否注销？");
            if(bt == QMessageBox::Yes)
            {
                while(true)
                {
                    sql_str = "update com_loginlog set logout_date = sysdate where log_index ='" + qro->value(0).toString() + "'";
                    qro_t->exec(sql_str);
                    if(!qro->next())
                    {
                        break;
                    }
                }

            }

        }


        qro->prepare("insert into com_loginlog (log_index, empl_code, empl_name,login_date,"
                  " dept_code, dept_name, sid, serial,log_machine, group_name, si_code"
                     ") values(:log_index, :empl_code, "
                  ":empl_name, sysdate, :dept_code, :dept_name, :sid, :serial,"
                     ":log_machine, :group_name, :si_code)");
        qro->bindValue(":log_index", pub::LOGINSESSION);
        qro->bindValue(":empl_code", pub::usr_code);
        qro->bindValue(":empl_name", pub::usr_name);
        qro->bindValue(":dept_code", pub::dp_code);
        qro->bindValue(":dept_name", pub::dp_name);
        qro->bindValue(":sid", sid);
        qro->bindValue(":serial", serial);
        qro->bindValue(":si_code", pub::dr_codg);
        qro->bindValue(":log_machine", QHostInfo::localHostName());
        qro->bindValue(":group_name", ui->cbDepartment->currentText());
        qro->exec();

        this->close();
    }else{
        errorCount ++;
        if(errorCount > 2){
            pub::userValidated = false;
            this->close();
        }
    }
}

void Dialog_signin::on_pbCancel_clicked()
{
    pub::userValidated = false;
    this->close();
}

void Dialog_signin::on_leUserCode_returnPressed()
{
    //if(ui->leUserCode->text().trimmed().isEmpty()){
    if(ui->cbDepartment->currentText().isEmpty()){
        QMessageBox::warning(this, "注意", "输入的用户代码无效！");
        return;
    }else{
        ui->lePassword->setFocus();
    }
}

void Dialog_signin::on_lePassword_returnPressed()
{
    if(ui->lePassword->text().trimmed().isEmpty()){
        return;
    }else{
        ui->pbOk->setFocus();
        //ui->cbDepartment->setFocus();
    }
}

void Dialog_signin::keyPressEvent(QKeyEvent *e)
{
    Q_UNUSED(e)
//    if(ui->cbDepartment->hasFocus()){
//        if(e->key() == Qt::Key_Enter){
//            if(!ui->cbDepartment->currentText().isEmpty()){
//                ui->pbOk->setFocus();
//            }
//        }
//    }

}

void Dialog_signin::on_leUserCode_textChanged(const QString &arg1)
{
    //输入代码位数满足检索条件，检索该代码关联的科室
    QString code = arg1.trimmed();
    if(code.length() == 6)
    {
        qrm->exec("select role_dept "
                  " from com_privileges "
                  " where type = 'dept' and code = '"+arg1+"' order by role_dept");

        if(!qrm->next()){
            QMessageBox::warning(this, "注意", "输入的用户代码无效！");
            return;
        }
        ui->cbDepartment->clear();
        while(true){
            ui->cbDepartment->addItem(qrm->value(0).toString());
            if(!qrm->next()){
                break;
            }
        }

        ui->cbDepartment->setCurrentText(defaultDept);
    }
    else if(code.length() > 6)
    {
        QMessageBox::warning(this, "注意", "用户代码超长！");
        return;
    }
}

void Dialog_signin::on_cbDepartment_currentTextChanged(const QString &arg1)
{
    pub::dp_name = arg1;
    qro_t->exec("select dept_code,standard_code,standard_name "
                "from com_department where dept_name = '" + arg1 + "'");
    qro_t->next();
    pub::dp_code = qro_t->value(0).toString();
    pub::dp_code_st = qro_t->value(1).toString();
    pub::dp_name_st = qro_t->value(2).toString();
}
